#ifndef __UDSF_FT232_C__
#define __UDSF_FT232_C__

#include "app.h"
/*
*   notice:
*   UDSF 同UDF编程：不可调用cstd-lib,只可调用"sdk_ifs_udk_cfg.h"、"sys_api.h"中列出的API函数。
*   UDSF文件内函数均需使用static修饰符，且UDF中以#include "udsf_xxx.c"形式引用
*/

#include "udsf_spi.c"
#include "udsf_delay.c"

static void udsf_ft232_init(void){
	FT232_CS_PIN = 1;
	GPIO->PMODE |= (1<<FT232_CS_PIN_ID);
	udsf_usci0_spi_init_without_cs(FT232_CS_PIN_ID,0,0,1); // lsb
}

static void udsf_ft232_deinit(void){
	FT232_CS_PIN = 1;
	GPIO->PMODE &= (~(1<<FT232_CS_PIN_ID));
	udsf_usci0_spi_deinit_without_cs();
}

static void udsf_ft232_send_data(uint8_t *data,int len){
	FT232_CS_PIN = 0;
	USCI0->TRX = 0x00;
	while((USCI0->ISR&USCI_ISR_TXE_Msk)==0);
	udsf_usci0_spi_rw_without_cs(data,len,NULL,0);
	FT232_CS_PIN = 1;
}

static void udsf_ft232_send_data_trans(uint8_t *data,int len){
	FT232_CS_PIN = 0;
	USCI0->TRX = 0x00;
	while((USCI0->ISR&USCI_ISR_TXE_Msk)==0);
	udsf_usci0_spi_send_data_trans_without_cs(data,len);
	FT232_CS_PIN = 1;
}

static void udsf_ft232_send_string(char *string){	

	FT232_CS_PIN = 0;
	USCI0->TRX = 0x00;
	while((USCI0->ISR&USCI_ISR_TXE_Msk)==0);
	int len = udsf_strlen(string);
	udsf_usci0_spi_rw_without_cs((uint8_t*)string,len,NULL,0);
	FT232_CS_PIN = 1;
}

/*endian: 0 -> little-endian 1-> big-enndian*/
static void udsf_ft232_send_u32_base16(int endian,uint32_t* Data,int data_len,char* start,char*end){
	uint8_t data[4];
	
	if( start ){
		udsf_ft232_send_string(start);
	}
	
	FT232_CS_PIN = 0;	
	USCI0->TRX = 0x00;
	while((USCI0->ISR&USCI_ISR_TXE_Msk)==0);
	for ( int i = 0;i<data_len;i++){
		if( endian == 0 ){
			*((uint32_t*)(&data)) = Data[i];
		}else{
			data[0] = Data[i]>>24;
			data[1] = Data[i]>>16;
			data[2] = Data[i]>>8;
			data[3] = Data[i];
		}
		udsf_usci0_spi_send_data_base16_without_cs(data,sizeof(data));
	}
	
	FT232_CS_PIN = 1;	
	
	if( end ){
		udsf_ft232_send_string(end);
	}
}

static void udsf_ft232_send_u16_base16(int endian,uint16_t* Data,int data_len,char* start,char*end){

	uint8_t data[2];
	
	if( start ){
		udsf_ft232_send_string(start);
	}
	
	FT232_CS_PIN = 0;
	USCI0->TRX = 0x00;
	while((USCI0->ISR&USCI_ISR_TXE_Msk)==0);
	for ( int i = 0;i<data_len;i++){
		if( endian == 0 ){
			*((uint16_t*)(&data)) = Data[i];
		}else{
			data[0] = Data[i]>>8;
			data[1] = Data[i];
		}
		udsf_usci0_spi_send_data_base16_without_cs(data,sizeof(data));
	}
	FT232_CS_PIN = 1;
	
	if( end ){
		udsf_ft232_send_string(end);
	}
	
}
static void udsf_ft232_send_u8_base16(uint8_t* Data,int data_len,char* start,char*end){
	
	if( start ){
		udsf_ft232_send_string(start);
	}

	FT232_CS_PIN = 0;
	USCI0->TRX = 0x00;
	while((USCI0->ISR&USCI_ISR_TXE_Msk)==0);
	udsf_usci0_spi_send_data_base16_without_cs(Data,data_len);
	
	FT232_CS_PIN = 1;
	
	if( end ){
		udsf_ft232_send_string(end);
	}
}



#endif
